package zifuchuan;

public class _12最大回文子串 {
    public static void main(String[] args) {
        String s = "ABDCDCBABC";
        System.out.println(force(s));
        System.out.println(DynamicIsPalindromic(s));
    }

    //暴力遍历
    public static String force(String s) {
        String ans = "";
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j < s.length(); j++) {
                String sub = s.substring(i, j+1);
                if (isPalindromic(sub) && sub.length() > max) {
                    ans = sub;
                    max = j - i;
                }
            }
        }
        return ans;
    }

    //动态规划解法
    public static String DynamicIsPalindromic(String s) {
        int len = s.length();
        if (len <= 1) return s;
        //状态容器--->表格
        Boolean[][] dp = new Boolean[len][len];
        //对角线上的都为true（即i==j的情况）
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }
        int max =1;
        int start = 0;
        for (int j = 1; j < len; j++) {
            for (int i = 0; i < len - 1 && i < j; i++){
                if (s.charAt(i) != s.charAt(j)){
                    dp[i][j] = false;
                }else {
                    if (j - i <= 2){
                        dp[i][j] = true;
                    }else {
                        dp[i][j] =dp[i+1][j-1];
                    }
                }
                if (dp[i][j] && j-i+1 > max){
                    max = j-i+1;
                    start = i;
                }
            }
        }
        return s.substring(start,start+max);
    }


    public static Boolean isPalindromic(String s) {
        if (s.length() == 0) {
            return false;
        }
        StringBuilder sb = new StringBuilder(s);
        return sb.reverse().toString().equals(s);
    }
}
